package com.taku.adprofadapter;

import static com.taku.adprofadapter.AdprofInitNetwork.getAppId;
import static com.taku.adprofadapter.AdprofInitNetwork.getCodeId;
import static com.taku.adprofadapter.AdprofInitNetwork.getExpressAD;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.adprof.sdk.api.AdError;
import com.adprof.sdk.api.AdRequest;
import com.adprof.sdk.api.NativeAd;
import com.adprof.sdk.api.NativeAdData;
import com.adprof.sdk.api.NativeAdLoadListener;
import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.core.api.ATInitMediation;
import com.anythink.core.api.MediationInitCallback;
import com.anythink.nativead.unitgroup.api.CustomNativeAd;
import com.anythink.nativead.unitgroup.api.CustomNativeAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class AdprofNativeAdapter extends CustomNativeAdapter {

    private static final String TAG = AdprofInitNetwork.TAG;

    NativeAd nativeAd;

    String mAppId;
    String codeId;

    boolean mVideoMuted;
    int mVideoAutoPlay;
    int mVideoDuration;

    boolean isC2SBidding = false;

    boolean expressAD = true;

    @Override
    public boolean startBiddingRequest(Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra, ATBiddingListener biddingListener) {
        Log.d(TAG, "\n native startBiddingRequest   serverExtra = " + serverExtra + "   localExtra = " + localExtra + "   biddingListener = " + biddingListener);

        isC2SBidding = true;

        loadCustomNetworkAd(context, serverExtra, localExtra);

        return true;
    }

    void initRequestParams(Map<String, Object> serverExtra, Map<String, Object> localExtra) {

        mAppId = getAppId(serverExtra);
        codeId = getCodeId(serverExtra);

        expressAD = getExpressAD(serverExtra);

        Log.d(TAG, "----native initRequestParams    " + mAppId + "   codeId = " + codeId + " " + serverExtra);

        mVideoMuted = ATInitMediation.getIntFromMap(serverExtra, "video_muted", 0) == 1;
        mVideoAutoPlay = ATInitMediation.getIntFromMap(serverExtra, "video_autoplay", 1);
        mVideoDuration = ATInitMediation.getIntFromMap(serverExtra, "video_duration", -1);
    }

    @Override
    public void loadCustomNetworkAd(final Context context, final Map<String, Object> serverExtra, Map<String, Object> localExtra) {

        initRequestParams(serverExtra, localExtra);

        if (TextUtils.isEmpty(mAppId)) {
            notifyATLoadFail("", "Adprof appid is empty");
            return;
        }

        AdprofInitNetwork.getInstance().initSDK(context, serverExtra, new MediationInitCallback() {
            @Override
            public void onSuccess() {
                startLoadAd(context, serverExtra, localExtra);
            }

            @Override
            public void onFail(String errorMsg) {
                notifyATLoadFail("", errorMsg);
            }
        });
    }

    private void startLoadAd(Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra) {
        try {
            loadRenderingAd(context.getApplicationContext(), serverExtra, localExtra);
        } catch (Throwable e) {
            notifyATLoadFail("", e.getMessage());
        }
    }

    private void loadRenderingAd(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra) {
        AdRequest adRequest = new AdRequest
                .Builder()
                .setCodeId(codeId)
                .setIsExpressAd(expressAD)
                .build();

        nativeAd = new NativeAd(adRequest, new NativeAdLoadListener() {

            @Override
            public void onAdError(AdError error) {
                notifyATLoadFail(error.getErrorCode() + "", error.getMessage());
            }

            @Override
            public void onAdLoad(List<NativeAdData> list) {

                try {

                    if (list != null && !list.isEmpty()) {

                        if (isC2SBidding) {

                            NativeAdData unifiedADData = list.get(0);

                            if (unifiedADData != null && mBiddingListener != null) {
                                double price = unifiedADData.getBidPrice();

                                AdprofNativeAd gdtNativeAd = new AdprofNativeAd(context, unifiedADData, mVideoMuted, mVideoAutoPlay, mVideoDuration, serverExtra, localExtra);

                                AdprofBiddingNotify notice = new AdprofBiddingNotify(nativeAd);

                                Log.d(TAG, "onAdLoad: onC2SBiddingResultWithCache price = " + price);

                                mBiddingListener.onC2SBiddingResultWithCache(ATBiddingResult.success(price, System.currentTimeMillis() + "", notice, ATAdConst.CURRENCY.RMB_CENT), gdtNativeAd);
                            }

                            return;
                        }

                        List<CustomNativeAd> resultList = new ArrayList<>();

                        for (NativeAdData unifiedADData : list) {
                            AdprofNativeAd gdtNativeAd = new AdprofNativeAd(context, unifiedADData, mVideoMuted, mVideoAutoPlay, mVideoDuration, serverExtra, localExtra);
                            resultList.add(gdtNativeAd);
                        }

                        CustomNativeAd[] customNativeAds = new CustomNativeAd[resultList.size()];
                        customNativeAds = resultList.toArray(customNativeAds);

                        if (mLoadListener != null) {
                            mLoadListener.onAdCacheLoaded(customNativeAds);
                        }

                    } else {
                        notifyATLoadFail("", "Ad list is empty");
                    }
                } catch (Exception e) {
                    Log.d(TAG, "onAdLoad: " + Log.getStackTraceString(e));
                }

            }

        });

        nativeAd.loadAd();
    }

    @Override
    public String getNetworkName() {
        return AdprofInitNetwork.getInstance().getNetworkName();
    }

    @Override
    public String getNetworkPlacementId() {
        return codeId;
    }

    @Override
    public String getNetworkSDKVersion() {
        return AdprofInitNetwork.getInstance().getNetworkVersion();
    }

    @Override
    public ATInitMediation getMediationInitManager() {
        return AdprofInitNetwork.getInstance();
    }

    @Override
    public void destory() {
        try {
            if (nativeAd != null) {
                nativeAd.destroyAd();
            }
        } catch (Exception e) {
            Log.d(TAG, "destory " + Log.getStackTraceString(e));
        }
    }

}
